package edu.ruc.cluster.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo;

import edu.ruc.cluster.util.*;

public class CommandInteraction {

	private DefaultLogHandler logHandler = null;
	public CommandInteraction(){
		logHandler = DefaultLogHandler.getInstance();
	}
	public static class MyUserInfo implements UserInfo{
		private String passwd = "";
		public String getPassphrase(){
			return null;
		}
		public String getPassword(){
			return passwd;
		}
		public boolean promptPassword(String message){
			passwd = "111111";
			return true;
		}
		public boolean promptPassphrase(String message){
			return true;
		}
		public boolean promptYesNo(String message){
			return true;
		}
		public void showMessage(String message){
			System.out.println(message);
		}
	}
	public void testJsch(String host, String cmd){
		try{
		      JSch jsch=new JSch();  

		      String user=host.substring(0, host.indexOf('@'));
		      host=host.substring(host.indexOf('@')+1);

		      Session session=jsch.getSession(user, host, 22);		
		      System.out.println("User: " + user + " host:" + host);
//		      UserInfo ui=new Sudo.MyUserInfo();
		      UserInfo ui = new MyUserInfo();
		      session.setUserInfo(ui);
		      session.setPassword("111111".getBytes());
		      session.connect();
		      System.out.println("after session.connect()");
		      
		      Channel channel = session.openChannel("exec");
		   
		      // man sudo
		      //   -S  The -S (stdin) option causes sudo to read the password from the
		      //       standard input instead of the terminal device.
		      //   -p  The -p (prompt) option allows you to override the default
		      //       password prompt and use a custom one.
//		      ((ChannelExec)channel).setCommand("sudo -S -p '' "+cmd);
		      ((ChannelExec)channel).setCommand(cmd);

		      InputStream in=channel.getInputStream();
		      OutputStream out=channel.getOutputStream();
		      ((ChannelExec)channel).setErrStream(System.err);
		      // this command is very very important!!!!!!!
		      ((ChannelExec)channel).setPty(true);

		      channel.connect();

//		      out.write((sudo_pass+"\n").getBytes());
////		      out.write(("1\n").getBytes());
//		      out.flush();

		      BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		      char[] cbuf = new char[100];
		      int ret = reader.read(cbuf);
				while(ret != -1){
					String str = new String(cbuf, 0, ret);
					System.out.println(str);
					if(str.contains("yes/no")){
						out.write("yes\n".getBytes());
						out.flush();
					}else if(str.contains("password")){
						out.write("111111\n".getBytes());
						out.flush();
					}
					ret = reader.read(cbuf);
				}
	/*	      
		      byte[] tmp=new byte[1024];
		      int count = 0;
		      while(true){
		        while(in.available()>0){
//		    	while(true){
		          int i=in.read(tmp, 0, 1024);
		          System.out.println(i);
		          if(i<0){
		        	  System.out.println("break " + count );
		        	  count ++;
		        	  break;
		        	  
		          }
		          String str = new String(tmp, 0, i);
		          System.out.print(str);
//		          if(str.contains("file")){
//		        	  out.write("\n".getBytes());
//		        	  out.flush();
//		          }
//		          if(str.contains("selection")){
//		        	  out.write(("2\n").getBytes());
//		        	  out.flush();
//		          }
//		          if(str.contains("UNIX password")){
//		        	  out.write(("111111\n").getBytes());
//		        	  out.flush();
//		          }
		          if(str.contains("yes/no")){
		        	  out.write(("yes\n").getBytes());
		        	  out.flush();
		          }
		          else if(str.contains("password")){
		        	  out.write(("111111\n").getBytes());
		        	  out.flush();
		          }
		        }
		        if(channel.isClosed()){
		          System.out.println("exit-status: "+channel.getExitStatus());
		          break;
		        }
		        try{Thread.sleep(1000);}catch(Exception ee){}
//		        System.out.println("wait: " + count++);
		      }*/
		      channel.disconnect();
		      session.disconnect();
		    }
		    catch(Exception e){
		      logHandler.error(this.getClass().getSimpleName() + " " + e.getMessage(), e);
		    }
		    
	  }
	
	public void testCommand(String[] command){
		try{
			/*
			Process p1 = null;
			if(command.length == 1){
				System.out.println(command[0]);
				p1 = Runtime.getRuntime().exec(command[0]);
			}
			else
			 	p1 = Runtime.getRuntime().exec(command);
			*/
			final Process p1 = Runtime.getRuntime().exec(command);
//			System.out.println(command.toString());
//			OutputStreamWriter writer = new OutputStreamWriter(p1.getOutputStream());
//			boolean ask = false;
			
//			new Thread(new Runnable(){
//				public void run(){
//					try{
//						p1.getOutputStream().write("111111\n".getBytes());
//						p1.getOutputStream().flush();
//					}catch(IOException e){
//						e.printStackTrace();
//					}
//				}
//			}).start();
			
			
			new Thread(new Runnable(){
				public void run(){
					BufferedReader error = new BufferedReader(new InputStreamReader(p1.getErrorStream()));
					String str = null;
					try{
						while((str = error.readLine()) != null){
							logHandler.error(str);
						}
						error.close();
					}catch(IOException e){
//						expHandler.handle(e);
						logHandler.error("thread Error Stream", e);
					}
				}
			}).start();
			
			new Thread(new Runnable(){
				public void run(){
					BufferedReader reader = new BufferedReader(new InputStreamReader(p1.getInputStream()));
					String str = null;
					try{
						while((str = reader.readLine()) != null){
//							if(str.indexOf("password") != -1)
//								ask = true;
							logHandler.info(str);
						}
						reader.close();
					}catch(IOException e){
//						expHandler.handle(e);
						logHandler.error("thread Input Stream", e);
					}
				}
			}).start();
			
			if(command[2].contains("alternatives")){
				OutputStream out = p1.getOutputStream();
				out.write("111111\n".getBytes());
				out.write("1\n".getBytes());
			}
			
//			try{
//				p1.waitFor();
//			}catch(InterruptedException e){
//				expHandler.handle(e);
//			}
			
			/*
			String str = "";
			
			System.out.println("aaa");
			while((str = error.readLine()) != null){
				logHandler.error(str);
			}
			System.out.println("bbb");
			while((str = reader.readLine()) != null){
				logHandler.info(str);
				if(str.indexOf("password") != -1){
					ask = true;
				}
//				if(-1 != str.indexOf("ttl")){
//					p1.destroy();
//					break;
//				}				
			}
			System.out.println("ccc");
			if(ask == true){
				writer.append("111111\r\n");
				writer.flush();
			}
			
			reader.close();			
			writer.close();
			*/
		}catch(IOException e){
			logHandler.error("Error to execute runtime", e);
//			expHandler.handle(e);
		}
				
	}
//	public void testCommand(String command){
//		String[] commands = new String[1];
//		commands[0] = command;
//		testCommand(commands);
//	}
	
	public void callSsh(){
		
		CommandInteraction ci = new CommandInteraction();
		String[] ssh = {
		"/bin/sh", "-c", "ssh deke@dlnode17 \"ping dlnode19\""
		};
		ci.testCommand(ssh);
		String[] pipe = {
				"/bin/sh", "-c", "ls /etc | grep hosts"
		};
		ci.testCommand(pipe);
		String[] copy = {
				"/bin/bash", "-c", "echo 111111 | sudo cp /etc/hosts /etc/hosts-back"
		};
		ci.testCommand(copy);
//		String[] ssh1 = {
//				"/bin/bash", "-c", "ssh-copy-id -i ~/.ssh/id_rsa.pub deke@10.77.110.229"
//		};
		String[] ssh2 = {
				"/bin/bash", "-c", "ssh deke@dlnode27 \"sudo -S -p '' /usr/sbin/update-alternatives --config java\""
		};
		String[] result = {
				"/bin/bash", "-c", "ssh -t deke@dlnode27 \"java -version\""
		};
//		String[] py = {
//				"python", "/home/deke/yt/pythonsrc/test.py"
//		};
		ci.testCommand(ssh2);
		ci.testCommand(result);
	}
	
	/*
	public static void main(String[] args){
		
		CommandInteraction ci = new CommandInteraction();
		String host = "deke@dlnode27";
		String configJava = "/usr/sbin/update-alternatives --config java";
		String cp = "cp /etc/hosts /etc/hosts-heyhey";
		String ls = "ls /etc/ | grep hosts";
		String rm = "rm /etc/hosts-heyhey";
		String adduser = "/usr/sbin/useradd test";
		String pw = "passwd test";
		String sshcopyid = "ssh-copy-id -i ~/.ssh/id_rsa deke@dlnode19";
		String sshkey = "ssh-keygen -t rsa -P \"\" ";
//		ci.testJsch(host, sshkey);
		ci.testJsch(host, sshcopyid);
//		ci.testJsch(host, adduser);
//		ci.testJsch(host, pw);
//		ci.testJsch(host, configJava);
//		ci.testJsch(host, cp);
//		ci.testJsch(host, ls);
//		ci.testJsch(host rm);
//		ci.testJsch(host, ls);	

	}
	*/
}
